package com.android.mybase.ui

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.WindowManager
import com.android.mybase.databinding.DialogDefaultBinding

class DefaultDialog : Dialog {
    private var btnCallback: BtnCallback? = null
    private var title: String? = null
    private var content: String? = null
    private var updateText = false
    private lateinit var binding: DialogDefaultBinding

    constructor(context: Context, btnCallback: BtnCallback) : super(context) {
        this.btnCallback = btnCallback
    }

    constructor(context: Context, title: String, content: String, btnCallback: BtnCallback) : super(context) {
        this.updateText = true
        this.btnCallback = btnCallback
        this.title = title
        this.content = content
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DialogDefaultBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setCanceledOnTouchOutside(true)
        
        window?.apply {
            setBackgroundDrawableResource(android.R.color.transparent)
            attributes = attributes.apply {
                gravity = Gravity.CENTER
                width = getWidth(context) * 260 / 376
            }
        }

        if (updateText) {
            title?.let { binding.titleTv.text = it }
            content?.let { binding.textTip.text = it }
        }

        binding.textLeft.setOnClickListener {
            btnCallback?.cancel()
            dismiss()
        }

        binding.textRight.setOnClickListener {
            btnCallback?.commit()
            dismiss()
        }
    }

    interface BtnCallback {
        fun commit()
        fun cancel()
    }

    private fun getWidth(context: Context): Int {
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val outMetrics = DisplayMetrics()
        wm.defaultDisplay.getMetrics(outMetrics)
        return outMetrics.widthPixels
    }
}